package com.cbs.utils;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.view.View;
import com.cbs.log.L;

/**
 * Created by broche on 3/31/14.
 */
public final class Graphics {
    private static final String TAG = Graphics.class.getName();

    public static Bitmap view2Bitmap(View view) {
        Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas();
        canvas.setBitmap(bitmap);
        view.draw(canvas);
        canvas.save(Canvas.ALL_SAVE_FLAG);
        canvas.restore();
        return bitmap;
    }

    public static Bitmap modifyImageAddAtPosition(Bitmap originBitmap, Bitmap newBitmap, float left, float top) {
        Canvas canvas = new Canvas(originBitmap);
        canvas.drawBitmap(newBitmap, left, top, null);
        canvas.save(Canvas.ALL_SAVE_FLAG);
        canvas.restore();
        return originBitmap;
    }

    public static Bitmap cutImage(Bitmap bitmap, Rect rect) {
        if (bitmap != null) {
            try {
                return Bitmap.createBitmap(bitmap, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top);
            } catch (Exception e) {
                L.e(TAG, "", e);
            }
        }
        return null;
    }

    public static Bitmap cutZoomImage(Bitmap bitmap, Rect rect, float scale) {
        if (bitmap != null) {
            try {
                Matrix matrix = new Matrix();
                matrix.postScale(scale, scale);
                return Bitmap.createBitmap(bitmap, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, matrix, true);
            } catch (Exception e) {
                L.e(Graphics.class.getName(), e.getMessage());
            }
        }
        return null;
    }

    public static Bitmap zoomImage(Bitmap bitmap, float destWidth, float destHeight) {
        if (bitmap != null && destWidth > 0 && destHeight > 0) {
            int oldWidth = bitmap.getWidth();
            int oldHeight = bitmap.getHeight();
            Matrix matrix = new Matrix();
            float widthScale = destWidth / oldWidth;
            float heightScale = destHeight / oldHeight;
            matrix.postScale(widthScale, heightScale);
            return Bitmap.createBitmap(bitmap, 0, 0, oldWidth, oldHeight, matrix, true);
        }
        return null;
    }
}
